package com.xiaoyu.lanling.feature.moment.controller.detail

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.view.list.BaseListViewController
import com.xiaoyu.lanling.event.moment.detail.LikeListEvent
import com.xiaoyu.lanling.event.moment.detail.LikeMomentEvent
import com.xiaoyu.lanling.feature.moment.model.detail.LikeItem
import com.xiaoyu.lanling.feature.moment.viewholder.detail.LikeItemViewHolder
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LikeDetailListController(context: Context, listData: PagedListDataModelWithRequestTag<LikeItem, Any>, adapter: CubeRecyclerViewSimpleAdapter<LikeItem>, swipeRefreshLayout: SwipeRefreshLayout, recyclerView: RecyclerView) : BaseListViewController<LikeItem, Any>(context, listData, adapter, swipeRefreshLayout, recyclerView) {

    companion object {

        fun create(context: Context, listData: PagedListDataModelWithRequestTag<LikeItem, Any>, swipeRefreshLayout: SwipeRefreshLayout, recyclerView: RecyclerView): LikeDetailListController {
            val adapter = CubeRecyclerViewSimpleAdapter<LikeItem>()
            adapter.setViewHolderClass(0, null, LikeItemViewHolder::class.java, 20)

            val controller = LikeDetailListController(context, listData, adapter, swipeRefreshLayout, recyclerView)

            AppEventBus.bindContainerAndHandler(context, object : SimpleEventHandler() {

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onEvent(event: LikeListEvent) {
                    controller.onListEvent(event)
                }

                @Subscribe(threadMode = ThreadMode.MAIN)
                fun onEvent(event: LikeMomentEvent) {
                    val index = adapter.list.indexOfFirst { it.user.uid == event.likeItem.user.uid }
                    if (index == -1) {
                        adapter.list.add(event.likeItem)
                        adapter.notifyItemInserted(adapter.list.lastIndex)
                    } else {
                        adapter.list.removeAt(index)
                        adapter.notifyItemRemoved(index)
                    }
                }
            })

            return controller
        }
    }
}